<?php
/**
 * @title 34. 在排序数组中查找元素的第一个和最后一个位置 - 二分
 * @author start2004
 */



class Solution {

    /**
     * @param Integer[] $nums
     * @param Integer $target
     * @return Integer[]
     */
    function searchRange($nums, $target) {
        /**
         * @since 2020-12-01 长度
         */
        $len = count($nums);
        if($len == 0){
            return [-1, -1];
        } else {}

        /**
         * @since 2020-12-01 二分区间起点
         */
        $left = 0;
        $right = $len-1;
        while($right-$left >= 2){
            $mid = ($left+$right)>>1;
            $val = $nums[$mid];

            /**
             * @since 2020-12-01 移动左右指针
             */
            if($val >= $target){
                $right = $mid;
            } else {
                $left = $mid;
            }
        }

        /**
         * @since 2020-12-01 确定起点
         */
        if($right == $left){
            if($nums[$left] == $target){
                $s = $left;
            } else {
                return [-1, -1];
            }
        } else {
            if($nums[$left] == $target){
                $s = $left;
            } elseif($nums[$right] == $target) {
                $s = $right;
            } else {
                return [-1, -1];
            }
        }
        // return $s;

        /**
         * @since 2020-12-01 二分区间终点
         */
        $left = 0;
        $right = $len-1;
        while($right-$left >= 2){
            $mid = ($left+$right)>>1;
            $val = $nums[$mid];

            /**
             * @since 2020-12-01 移动左右指针
             */
            if($val <= $target){
                $left = $mid;
            } else {
                $right = $mid;
            }
        }

        /**
         * @since 2020-12-01 确定终点
         */
        if($right == $left){
            if($nums[$right] == $target){
                $e = $right;
            } else {
                return [-1, -1];
            }
        } else {
            if($nums[$right] == $target){
                $e = $right;
            } elseif($nums[$left] == $target) {
                $e = $left;
            } else {
                return [-1, -1];
            }
        }

        /**
         * @return
         */
        return [$s, $e];
    }
}




/**
 * @url http://127.0.0.1/leetcode/202007/2020.07.04_7.php
 */
$datas = [
    [[5,7,7,8,8,10], 8],
    [[5,7,7,8,8,10], 6],
];

include_once dirname(__DIR__) . DIRECTORY_SEPARATOR ."xhprof.php";
$xhprof = new Xhprof();
foreach ($datas as $data){
    var_dump($data);

    $obj = new Solution();
    $result = $obj->searchRange($data[0], $data[1]);
    var_dump($result);
    echo str_repeat("<br>", 3);
}
$xhprof->end();
